package com.alibaba.datax.elasticresource;

import java.text.ParseException;

import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.common.util.MessageSource;
import com.alibaba.datax.core.Engine;
import com.alibaba.datax.core.util.ConfigurationValidate;
import com.alibaba.datax.core.util.container.CoreConstant;
import com.leehom.arch.elastic.sharding.ShardingItemContext;
import com.leehom.arch.elasticjobx.simple.job.SimpleJob;
import com.leehom.arch.rbt.common.ConfigUtils;
import com.leehom.arch.rbt.common.exception.RBTErrorCode;
import com.leehom.arch.rbt.common.exception.RBTException;

public class DataxEngineJob implements SimpleJob {
    
    @Override
    public void execute(final ShardingItemContext shardingContext) {
    	// 解释出jobId
        String jobName = shardingContext.getRegName();
        // shardingId释出jobId, shardingId格式jobId_sn
        // appId：jobxxx
        String shardingId = shardingContext.getShardingItemId();
        //
        String appId;
        long jobId;
		try {
			appId = ConfigUtils.extractAppId(shardingId);
			jobId = ConfigUtils.extractJobId(appId);
		} catch (ParseException e) {
			// 不会发生的
			throw RBTException.asRbtException(RBTErrorCode.EXTRACT_SHARINGID_ERROR, e);
		}    
        // 执行模式 core.container.job.mode，分布式，
        String RUNTIME_MODE = "distribute";
        // 载入分片配置
        String configStr = shardingContext.getConfigData();
        Configuration configuration = Configuration.from(configStr);
        // 设置task group模式 CoreConstant.DATAX_CORE_CONTAINER_MODEL设置为工作组
        configuration.set(CoreConstant.DATAX_CORE_CONTAINER_MODEL, "taskGroup");
        // i18n
        MessageSource.init(configuration);
        MessageSource.reloadResourceBundle(Configuration.class);
        // 置入jobId，Job AppId
        configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_ID, jobId);
        configuration.set(CoreConstant.DATAX_CORE_CONTAINER_JOB_APPID, appId);
        // 验证配置
        ConfigurationValidate.doValidate(configuration);
        Engine engine = new Engine();
        engine.start(configuration, RUNTIME_MODE);
        
    }
    
}
